package com.druid.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.druid.entity.CeSecurityPermission;
import com.druid.entity.CeSecurityResource;
import com.druid.model.ResponseData;
import com.druid.request.RequestParamInterfaceGroup;
import com.druid.request.SecurityPermissionParam;
import com.druid.service.managementservice.ICeSecurityPermissionService;
import com.druid.service.managementservice.ICeSecurityResourceService;
import com.druid.util.ManagementException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @author druid-elf
 * @since 2020-01-09
 */
@Api(tags={"权限表前端控制器"})
@RestController
@RequestMapping("/ceSecurityPermission")
@RequiredArgsConstructor
public class CeSecurityPermissionController {

    private final ICeSecurityPermissionService iCeSecurityPermissionService;
    private final ICeSecurityResourceService iCeSecurityResourceService;

    @ApiOperation("得到权限列表")
    @GetMapping(value = "getCeSecurityPermissionList")
    public ResponseData<List<CeSecurityPermission>> getCeSecurityPermissionList() {

        return ResponseData.SUCCESS(
                iCeSecurityPermissionService.list()
        );
    }

    @ApiOperation("新增权限")
    @PostMapping("addSecurityPermission")
    public ResponseData<String> addSecurityPermission (@RequestBody @Validated(RequestParamInterfaceGroup.InsertGroup.class) SecurityPermissionParam securityPermissionParam ) {

        CeSecurityPermission securityPermission = CeSecurityPermission
                .builder()
                .name( securityPermissionParam.getName() )
                .build();

        return  iCeSecurityPermissionService.save( securityPermission )
                ? ResponseData.SUCCESS("操作成功")
                : ResponseData.FAILURE("操作失败");
    }

    @ApiOperation("删除权限")
    @PostMapping("deleteSecurityPermission")
    @Transactional
    public ResponseData<String> deleteSecurityPermission (@RequestBody @Validated(RequestParamInterfaceGroup.DeleteGroup.class) SecurityPermissionParam securityPermissionParam ) {

        //  删除权限表的数据
        if ( !iCeSecurityPermissionService.removeById( securityPermissionParam.getId()) ) {
            throw new ManagementException("删除权限表数据失败");
        }

        //  删除资源表数据
        if ( !iCeSecurityResourceService.remove(new LambdaQueryWrapper<CeSecurityResource>().eq(CeSecurityResource::getPermissionId,securityPermissionParam.getId()))) {
            throw new ManagementException("删除资源表数据失败");
        }

        return ResponseData.SUCCESS("操作成功");
    }
}
